<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2014/10/8
 * Time: 9:24
 */
class AttachmentController extends Controller{
    public function actions(){
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xf4f4f4,
                'padding'=>0,
                'height'=>30,
                'maxLength'=>4,
            ),
        );
    }
    public function actionIndex(){
        $this->smarty->display('index.html');
    }
    public function actionTest(){

        $this->smarty->assign('captcha', $this->widget('CCaptcha',array('showRefreshButton'=>false,'clickableImage'=>true,'imageOptions'=>array('alt'=>'点击换图','title'=>'点击换图','style'=>'cursor:pointer')), true));
        $this->smarty->display('test.html');
    }
    public function actionDo(){;
        $file = $_FILES['attachment']['tmp_name'];
        $name = $_FILES['attachment']['name'];
        $size = $_FILES['attachment']['size'];
        $content = file_get_contents($file);
        $fileObj = new File();
        echo $fileObj->uploadByFile($name, $file);
    }
    /**
     * 添加对标附件
     * 根据类型上传文件
     * 文件名为  网点名称-指标-序号
     */
    public function actionduibiaoAttach(){
        $attach_type = $this->request('attach_type');
        $nq_id = intval($this->request('nq_id'));
        $subject_id = intval($this->request('subject_id'));
        $network_id = intval($this->request('network_id'));
		$fileObj = new File();
        $bucket = isset($fileObj->attach_type[$attach_type]) ? $fileObj->attach_type[$attach_type] : 'other';
        $file = $_FILES['upfile']['tmp_name'];
        $name = trim($_FILES['upfile']['name']);
        $size = $_FILES['upfile']['size'];
        //$content = file_get_contents($file);
        
        //先判断此网点某一个问题已经传了多大的附件了，总的不能超过10M
        $connection=Yii::app()->db;
        $command=$connection->createCommand("SELECT SUM(filesize) FROM `question_benchmark_attach` where nq_id={$nq_id} and subject_id={$subject_id} and status=1");
        $sum =  $command->queryScalar();
        if (($sum+$size) > 10000000) {
            echo '{"url":"' . $url . '","state":"FAILD","note":"超出总大小10M"}';exit;
        }

        $network_info = NetWork::model()->findByPk($network_id)->attributes;
        $subject_info = QuestionSubject::model()->findByPk($subject_id)->attributes;
        $filename = $network_info['network_name'].'-'.$subject_info['question_num'].'-'.time().'.'.$fileObj->ext($name);
        
        /**
         * 20150509 将上传的对标附件，存到本地，方便下载使用
         * 文件名格式：网点编号(network_num)-问题编号(question_num)-自定义时间戳-网点ID(network_id)-网点问卷ID(nq_id)-题目ID(subject_id)
         */
        $dir = dirname(Yii::app()->BasePath) .'/assets/benchmark_attach/'.$subject_info['question_id'].'/';
        if (!is_dir($dir)) {
                @mkdir($dir);
        }
        $dir = str_replace(DIRECTORY_SEPARATOR, "/", $dir);
        $saveFileName = $network_info['network_num']."-".$subject_info['question_num'].'-'.time().'-'.$network_id."-".$nq_id."-".$subject_id.".".$fileObj->ext($name);
        @copy($file, $dir . $saveFileName);

        if ($url = $fileObj->uploadByFile($name, $file, $bucket, $filename)){        
            //判断是否上传了同名的文件，如果是就覆盖
            //if ($attach = QuestionBenchmarkAttach::model()->find("nq_id={$nq_id} and subject_id={$subject_id} and status=1 and filename='{$name}'")) {

            //} else {
                $attach = new QuestionBenchmarkAttach();
            //}
                
            $attach->nq_id = $nq_id;
            $attach->subject_id = $subject_id;
            $attach->fileurl = $url;
            $attach->attach_type = $bucket;
            $attach->network_id = $network_id;
            $attach->filename = $name;
            $attach->filesize = $size;
            if ($attach->save()){
                //对标里标识出有附件，便于显示和操作
                QuestionBenchmark::model()->updateAll(array('haveattach' => 1), 'nq_id=:nq_id and subject_id=:subject_id',array(':nq_id' => $nq_id, ':subject_id' => $subject_id));
                echo '{"url":"' . $url . '","state":"SUCCESS"}';exit;
            } else {
                echo '{"url":"' . $url . '","state":"FAILD","note":"保存上传失败"}';exit;
            }
        } else {
            echo '{"url":"' . $url . '","state":"FAILD","note":"上传阿里云失败"}';exit;
        }
    }
    /**
     * 报备附件
     */
    public function actionBaobei(){
        $attach_type = $this->request('attach_type');
        $network_id = intval($this->request('network_id'));
        $fileObj = new File();
        $bucket = isset($fileObj->attach_type[$attach_type]) ? $fileObj->attach_type[$attach_type] : 'other';
        $file = $_FILES['upfile']['tmp_name'];
        $name = $_FILES['upfile']['name'];
        $size = $_FILES['upfile']['size'];
        
        $network_info = NetWork::model()->findByPk($network_id);
        $download_name = $network_info['network_num'].'-'.$network_info['network_name'].'-'.rand(1,999).'-'.$name;
        
        $dir = dirname(Yii::app()->BasePath) .'/assets/report_attach/'.$network_id.'/';
        if (!is_dir($dir)) {
                @mkdir($dir);
        }
        $dir = str_replace(DIRECTORY_SEPARATOR, "/", $dir);
   
        @copy($file, $dir . $download_name);
        
        
        
        if ($url = $fileObj->uploadByFile($name, $file, $bucket,$download_name)){
            $attach = new NetworkReportAttach();
            $attach->nr_id = 0;
            $attach->network_id = $network_id;
            $attach->file_name = $download_name;
            $attach->url = $url;
            $attach->create_time = time();;
            if ($attach->save()){
                echo '{"url":"' . $url . '","state":"SUCCESS","id":"'.$attach->nra_id.'","file_name":"'.$name.'"}';
            } else {
                echo '{"url":"' . $url . '","state":"FAILD"}';
            }
        } else {
            echo '{"url":"' . $url . '","state":"FAILD"}';
        }
    }
    public function actionDotest(){
        $code = $_POST['code'];

        if ($this->createAction('captcha')->validate($code, false)){
            echo '验证码正确';
        } else {
            echo '验证码错误';
        }
    }
}